<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片式图 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type='primary'>添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表区域 -->
      <el-table :data="roleList" stripe border>
        <el-table-column type='expand'>
          <template slot-scope='scope'>
            <el-row v-for='(item1,i1) in scope.row.children' :key='item1.id' :class='["db",i1===0?"dt":"","vcenter"]'
              @close='removeRightById(scope.row,item1.id)'>
              <!-- 渲染一级权限 -->
              <el-col :span='5'>
                <el-tag closable>{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span='19'>
                <!-- 通过for循环渲染二级权限 -->
                <el-row v-for='(item2,i2) in item1.children' :key='item2.id' :class="[i2===0?'':'dt','vcenter']"
                  @close='removeRightById(scope.row,item2.id)'>
                  <el-col :span='6'>
                    <el-tag closable type='success'>{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span='18'>
                    <el-tag v-for='item3 in item2.children' :key='item3.id' type='warning' closable
                      @close='removeRightById(scope.row,item3.id)'>{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type='index' label='#'></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width='300px'>
          <template slot-scope='scope'>
            {{scope.row.sco}}
            <el-button size='mini' type="primary" icon="el-icon-edit" round>编辑</el-button>
            <el-button size='mini' type="danger" icon="el-icon-delete" round>删除</el-button>
            <el-button size='mini' type="warning" icon="el-icon-setting" round @click='showSetRightDialog(scope.row)'
              @close='setRightDialogClose'>
              分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 非分配权限 -->
    <el-dialog title="提示" :visible.sync="showSetRightVisible" width="50%" @click='setRightDialogClose'>
      <!-- 树形控件 -->
      <el-tree :data="treeList" :props="treeProps" show-checkbox node-key="id" default-expand-all
        :default-checked-keys="defKeys">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showSetRightVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights" ref='treeRef'>确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script scoped>
  export default {
    data() {
      return {
        // 树形控件的属性绑定对象
        treeProps: {
          children: 'children',
          label: 'authName'
        },
        showSetRightVisible: false,
        // 所有角色列表数据
        roleList: [],
        // 所有权限的数据
        treeList: [],
        // 默认选中的节点id值数组
        defKeys: [],
        roleId: ''
      }
    },
    created() {
      this.getRoleList()
    },
    methods: {
      async showSetRightDialog(row) {
        this.roleId = this.row.id
        const {
          data: res
        } = await this.$axios.get('rights/tree')
        if (res.meta.status !== 200) return this.$message.error('获取信息失败')
        this.treeList = res.data
        this.getLeafKeys(row, this.defKeys)
        this.showSetRightVisible = true
      },
      async getRoleList() {
        const {
          data: res
        } = await this.$axios({
          url: 'roles'
        })
        if (res.meta.status !== 200) return this.$message.error('获取角色列表失败!')
        this.roleList = res.data
      },
      async removeRightById(row, right) { // 根据id删除对应权限
        //  点击权限框出现弹框
        const confirmRsult = await this.$confirm('此操作将永久删除该标签, 是否继续?', '提示删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(async () => {
          if (confirmRsult !== 'confirm') {
            return this.$message.info('取消了删除！')
          }
          this.$message.info('已删除！')
          const {
            data: res
          } = await this.$axios.delete(`roles/${row.id}/rights/${right}`)
          if (res.meta.status !== 200) return this.$message.error('删除权限失败')
          row.children = res.data
        })
      },
      // 通过递归的形式，获取角色下所有三级权限的id，斌能够保存到defKeys数组中
      getLeafKeys(node, arr) {
        // 该函数会获取到当前角色的所有三级权限id并添加到defKeys中
        // 如果当前节点不包含children属性，则表示node为三级权限
        if (!node.children) {
          return arr.push(node.id)
        }
        // 递归调用
        node.children.forEach(item => this.getLeafKeys(item, arr))
      },
      setRightDialogClose() {
        // 当用户关闭树形权限对话框的时候，清除掉所有选中状态
        this.defKeys = []
      },
      async allotRights() {
        const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
        const idStr = keys.join(',')
        const {
          data: res
        } = await this.$axios({
          method: 'POST',
          url: `roles/${this.roleId}/rights`,
          data: {
            idStr
          }
        })
        if (res.meta.status !== 200) return this.$message.error('分配权限失败')
        this.$message.success('分配权限成功')
        this.getRoleList()
        this.showSetRightVisible = false
      }
    }
  }

</script>

<style scoped>
  .el-tag {
    margin: 7px;
  }

  .db {
    border-bottom: 1px solid #eee;
  }

  .dt {
    border-top: 1px solid #eee;
  }

  .vcenter {
    display: flex;
    align-items: center;
  }

</style>
